<template>
  <div class="coupon">
    <!-- 搜索 -->
    <el-space>
      <el-input placeholder="请输入优惠券标题" v-model="findFrom.title" />
      <el-select placeholder="请选择优惠券类型" v-model="findFrom.couType">
        <el-option :value="item.value" :label="item.label" v-for="item in selectType" :key="item.value" />
      </el-select>
      <el-select placeholder="请选择优惠券状态" v-model="findFrom.status">
        <el-option :value="item.value" :label="item.label" v-for="item in selectStatus" :key="item.value" />
      </el-select>
      <el-button type="primary" :icon="Search" @click="initData()" v-btnkey='"promotion:coupon:list"'>查找</el-button>
      <el-button type="primary" :icon="Plus" @click="add" v-btnkey='"promotion:coupon:create"'>添加</el-button>
      <el-button type="primary" :icon="Download" @click="exportExcel">当前页导出</el-button>
    </el-space>
    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%;margin-top:10px" id="exportTab" border :header-cell-style="{'text-align':'center'}" :cell-style="{'text-align':'center'}">
      <el-table-column label="优惠券Id" prop="id" width="150" sortable>
      </el-table-column>
      <el-table-column label="优惠券名称" prop="title" width="100">
      </el-table-column>
      <el-table-column label="优惠券类型" prop="type" width="100">
        <template #default="scope">
          {{scope.row.type==1?'满减券':'立减券'}}
        </template>
      </el-table-column>
      <el-table-column label="介绍" prop="description" width="100">
      </el-table-column>
      <el-table-column label="优惠券数量" prop="total" width="100">
      </el-table-column>
      <el-table-column label="剩余数量" prop="surplus" width="100">
      </el-table-column>
      <el-table-column label="每人限领" prop="limit" width="100">
      </el-table-column>
      <el-table-column label="满减金额" prop="discount" width="100">
        <template #default="scope">
          {{'减免'+scope.row.discount+'元可用'}}
        </template>
      </el-table-column>
      <el-table-column label="最低消费" prop="min" width="100">
        <template #default="scope">
          {{'满'+scope.row.min+'元可用'}}
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.gmtEnd<new Date().getTime()?'danger':scope.row.status?'success':'danger'">
            {{scope.row.gmtEnd<new Date().getTime()?'已过期':scope.row.status?'正常':'下架'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="使用类目名称" prop="categoryTitle" width="150">
        <template #default='scope'>
          <el-tag>
            {{scope.row.categoryTitle?scope.row.categoryTitle:'全场通用'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="使用类目ID" prop="categoryId" width="100">
      </el-table-column>
      <el-table-column label="领券相对天数" prop="days" width="100">
        <template #default='scope'>
          {{scope.row.days?scope.row.days:'无'}}
        </template>
      </el-table-column>
      <el-table-column label="领券开始时间" prop="gmtStart" width="100">
        <template #default='scope'>
          {{scope.row.gmtStart?new Date(scope.row.gmtStart).startTime():'无'}}
        </template>
      </el-table-column>
      <el-table-column label="领券结束时间" prop="gmtEnd" width="100">
        <template #default='scope'>
          {{scope.row.gmtEnd?new Date(scope.row.gmtEnd).startTime().substr(0,16):'无'}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleActivate( scope.row)">
            {{scope.row.gmtEnd<new Date().getTime()?'已过期':scope.row.status?'冻结':'激活'}}
          </el-button>
          <el-button size="small" type="primary"  @click="handleLook(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 创建弹出框  -->
    <el-dialog v-model="dialogFormVisible" :title="bool?'添加':'编辑'" :destroy-on-close='true'>
      <el-form :model="form" ref="formRef" :disabled='!bool'>
        <el-form-item label="优惠券名称" prop='title' :label-width="formLabelWidth" :rules='[{required:true,message:"请输入优惠券名称"}]'>
          <el-input v-model="form.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="优惠券类型" :label-width="formLabelWidth" prop='type' :rules='[{required:true,message:"请选择类型"}]'>
          <el-select v-model="form.type" placeholder="请选择">
            <el-option :label="item.label" :value="item.value" v-for="item in selectType.slice(0,2)" :key="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="介绍" :label-width="formLabelWidth">
          <el-input v-model="form.description" autocomplete="off" />
        </el-form-item>
        <el-form-item label="优惠券数量" :label-width="formLabelWidth" prop='total' :rules='[{required:true,message:"请输入优惠券数量"},{pattern: /^\d+$|^\d+[.]?\d+$/,message:"请输数字"}]'>
          <el-input v-model.trim="form.total" autocomplete="off" :rules='[{required:true,message:"请输入优惠券数量"},,{pattern: /^\d+$|^\d+[.]?\d+$/,message:"请输数字"}]'>
            <template #append>张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="每人限领" :label-width="formLabelWidth" prop='limit' :rules='[{required:true,message:"请输入每人限领数量"},{pattern: /^\d+$|^\d+[.]?\d+$/,message:"请输数字"}]'>
          <el-input v-model.trim="form.limit" autocomplete="off">
            <template #append>张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="优惠金额" :label-width="formLabelWidth" prop='discount' :rules='[{required:true,message:"请输入每人限领数量"},{pattern: /^\d+$|^\d+[.]?\d+$/,message:"请输数字"}]'>
          <el-input v-model.trim="form.discount" autocomplete="off">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="最低消费" :label-width="formLabelWidth" prop='min' :rules='[{required:true,message:"请输入每人限领数量"},{pattern: /^\d+$|^\d+[.]?\d+$/,message:"请输数字"}]'>
          <el-input v-model.trim="form.min" autocomplete="off">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="优惠券状态" :label-width="formLabelWidth" prop='status' :rules='[{required:true,message:"请选择状态"}]'>
          <el-select v-model="form.status" placeholder="请选择">
            <el-option :label="item.label" :value="item.value" v-for="item in selectStatus.slice(0,2)" :key="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="有效期" :label-width="formLabelWidth">
          <el-radio-group v-model="labelPosition" style="margin-bottom:10px">
            <el-radio-button :label="1">领券相对天数</el-radio-button>
            <el-radio-button :label="0">指定绝对时间</el-radio-button>
          </el-radio-group>
          <el-input v-if="labelPosition" v-model="form.days" autocomplete="off">
            <template #append>天</template>
          </el-input>
          <div class="block" v-else>
            <el-date-picker v-model="form.gmtStart" type="datetime" placeholder="请选择" value-format="x" :disabledDate='startDate' />
            <span style="width:50px;text-align:center">至</span>
            <el-date-picker v-model="form.gmtEnd" type="datetime" placeholder="请选择" value-format="x" :disabledDate='overDate' />
          </div>
        </el-form-item>
        <el-form-item label="商品限制范围" :label-width="formLabelWidth">
          <el-radio-group v-model="cut" style="margin-bottom:10px">
            <el-radio-button :label="0" @click="form.categoryId=''">全场通用</el-radio-button>
            <el-radio-button :label="1">指定分类</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优惠类目" :label-width="formLabelWidth" v-if="cut">
          <el-cascader :options="options" :props="part" clearable v-model="form.categoryId" :show-all-levels="false" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm('formRef')" v-if="bool">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分页 -->
    <paging v-bind="pageData" @pageChang="pageChang"></paging>
  </div>
</template>
<script>
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
import { Search, Plus, Download } from '@element-plus/icons-vue';
import paging from "@/components/Paging/Paging.vue";
import { post } from "@/utils/http";
import { debounce } from "@/utils/debounce";
export default {
  components: {
    paging
  },
  setup() {
    return {
      Search,
      Plus,
      Download
    }
  },
  data() {
    return {
      findFrom: {  //查找优惠券数据
        title: '',
        status: null,
        couType: null
      },
      selectType: [{ label: '满减券', value: 1 }, { label: '立减券', value: 2 }, { label: '全部', value: '' }], //选择优惠券类型
      selectStatus: [{ label: '下架', value: 0 }, { label: '正常', value: 1 }, { label: '已过期', value: -1 }, { label: '全部', value: '' }],  //选择优惠券类型
      tableData: [],  //表格列表
      pageData: {  //分页数据
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      labelPosition: 1, //切换有效期选择
      cut: 1,  //切换范围品类
      bool: false,  //标题判断
      form: { //添加数据
        title: '',
        type: '',
        description: '',
        total: 0,
        limit: 0,
        discount: 0,
        min: 0,
        gmtStart: null,
        gmtEnd: null,
        status: '',
        days: '',
        categoryId: ''
      },
      part: {  //子集数据
        checkStrictly: true,
        children: 'childrenList',
        value: 'id',
        label: 'title',
        emitPath: false  //选择最后一位子节点
      },
      dialogFormVisible: false,  //创建框显示
      formLabelWidth: '140px',
      options: [],  //类目数据
    }
  },
  methods: {
    initData() {
      post({ _gp: 'admin.coupon', _mt: 'list', title: this.findFrom.title, type: this.findFrom.couType, status: this.findFrom.status, pageNo: this.pageData.currentPage, limit: this.pageData.pageSize }).then(res => {
        let { errno, data,} = res
        if (errno == 200) {
          this.tableData = data.items
          this.pageData.total = data.total
        } else {
          ElMessage.warning(res.errmsg)
        }
      })
    },
    //改变状态
    handleActivate: debounce(function (row) {
      if (row.gmtEnd < new Date().getTime()) return ElMessage.error('过期优惠券，建议删除');
      let status = row.status ? 0 : 1
      post({ _gp: 'admin.coupon', _mt: 'updateCouponStatus', id: row.id, status: status }).then(res => {
        if (200 == res.errno) {
          ElMessage.success(status ? '正常' : '下架')
          this.initData()
        }
      })
    }, 500),

    // 导出
    exportExcel() {
      /* generate workbook object from table */
      var xlsxParam = { raw: true } // 导出的内容只做解析，不进行格式转换
      var wb = XLSX.utils.table_to_book(document.querySelector('#exportTab'), xlsxParam)
      /* get binary string as output */
      var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'fileName.xlsx')
      } catch (e) {
        if (typeof console !== 'undefined') {
          console.log(e, wbout)
        }
      }
      return wbout
    },
    // 添加
    add() {
      this.dialogFormVisible = true
      this.bool = true
      Object.assign(this.form, this.$options.data().form)  //赋值  最初始值
    },
    // 添加确定
    confirm(formRef) {
      this.labelPosition ? (this.form.gmtStart = '') && (this.form.gmtEnd = '') : this.form.days = ''
      this.$refs.formRef.validate(valid => {
        if (valid) {
          post({ _gp: 'admin.coupon', _mt: 'create', ...this.form }).then(res => {
            if (200 == res.errno) {
              console.log(this.form);
              this.dialogFormVisible = false
              ElMessage.success('成功')
              this.initData()
            }
          })
        }
      })
    },
    // 开始时间
    startDate(e) {
      return e.getTime() < Date.now()
    },
    // 结束
    overDate(e) {
      return this.form.gmtStart > e.getTime()
    },
    //查看
    handleLook(row) {
      this.form = {}
      this.labelPosition = row.gmtEnd && row.gmtEnd ? 0 : 1  //显示对应按钮
      this.cut = row.categoryId ? 1 : 0  //显示对应按钮
      Object.assign(this.form, row)  //赋值
      this.bool = false
      this.dialogFormVisible = true
      if (row.gmtEnd < new Date().getTime()) {
        this.form.status = '已过期'
      }
    },
    // 分页
    pageChang(e) {
      Object.assign(this.pageData, e)
      this.initData()
    },
  },
  created() {
    post({ _gp: 'admin.category', _mt: 'categoryTree' }).then(res => {
      this.options = res.data
    })
    this.initData()
  }
}
</script>
<style lang="less" scoped>
.block {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}
</style>